package org.momo.rpc.springboot.starter.bootstrap;

import lombok.extern.slf4j.Slf4j;
import org.momo.rpc.config.RpcConfigLoader;
import org.momo.rpc.config.config.RpcConfig;
import org.momo.rpc.extention.ExtensionLoader;
import org.momo.rpc.registry.ProviderRegistry;
import org.momo.rpc.server.Server;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

@Slf4j
public class RpcServerStarter implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        RpcConfig rpcConfig = RpcConfigLoader.getRpcConfig();

        try {
            // 启动 注册中心客户端
            ProviderRegistry providerRegistry = ExtensionLoader.getExtensionLoader(ProviderRegistry.class).getExtension(rpcConfig.getRegistry());
            providerRegistry.initRegistryClient(rpcConfig.getRegistryConfig());

            // 启动服务器
            Server server = ExtensionLoader.getExtensionLoader(Server.class).getExtension(rpcConfig.getServer());
            server.start(rpcConfig.getServerPort());

            Runtime.getRuntime().addShutdownHook(new Thread(server::stop));
            Runtime.getRuntime().addShutdownHook(new Thread(providerRegistry::closeRegistryClient));
        } catch (Exception e) {
            log.error("Server fail to start, error is {}", e.getMessage());
        }

        ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);
    }

}
